/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.ufpb.halloc.conexaoDB;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.ResourceBundle;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author leonardo
 */
public class Pool implements PoolIF {

    
    private DataSourceConnectionIF dsc;
    private ArrayBlockingQueue<Connection> connLivres;
    private HashMap<String, Connection> connOcupadas;
    private int maxconn;
    private ResourceBundle config;
    
        
    public Pool() {
    
        config = ResourceBundle.getBundle("br.com.ufpb.halloc.conexaoDB.bancoDeDados");
        
        dsc = new DataSourceConnection(config.getString("url"),     config.getString("driver"),
                                       config.getString("usuario"), config.getString("senha"));
        
        this.maxconn = Integer.parseInt(config.getString("numeroMaximoConexoes"));
        
        connLivres = new ArrayBlockingQueue<Connection>(maxconn, true);
        connOcupadas = new HashMap<String, Connection>();
    }
    
    @Override
    public Connection getConnection() {
        
        Connection connection = null;
        
        try {
            if(connOcupadas.size() < maxconn){            
                connection = connLivres.poll();
                if (connection == null){
                    connection = dsc.getConnection();
                } else if (connection.isClosed()){
                    this.getConnection();
                }
                connOcupadas.put(connection.toString(), connection);
            }
        } catch (SQLException ex) {
            Logger.getLogger(Pool.class.getName()).log(Level.SEVERE, null, ex);
        }
        return connection;
    }
    
    

    @Override
    public void liberarConnection(Connection conn) {
        if (connOcupadas.containsValue(conn)){
            this.connLivres.add(conn);
            this.connOcupadas.remove(conn.toString());
        }
        
    }
    
    
    
}
